//
//  AlarmReportView.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/4/27.
//

import Foundation
import UIKit
import AAInfographics

class AlarmReportView: UIScrollView {
    let baseV = AlarmStatisticsView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        showsVerticalScrollIndicator = false
        backgroundColor = .hex("#3C72FF")
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reloadUI(withModel model: AlarmStaticsModal?) {
        baseV.reloadUI(withModel: model)
    }
    
    // MARK: - Setup
    func setupUI() {
        addSubview(titleL)
        titleL.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(31)
            make.top.equalToSuperview().offset(6)
        }
        
        addSubview(deptBtn)
        deptBtn.snp.makeConstraints { make in
            make.left.equalTo(titleL.snp.left)
            make.top.equalTo(titleL.snp.bottom).offset(10)
            make.width.equalTo(120)
            make.height.equalTo(27)
        }
        
        addSubview(reportIV)
        reportIV.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(ScreenWidth - 170)
            make.top.equalToSuperview()
            make.height.equalTo(81)
            make.width.equalTo(144)
        }
        
        addSubview(baseV)
        baseV.snp.makeConstraints { make in
            make.top.equalTo(reportIV.snp.bottom)
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenWidth - 20)
            make.height.equalTo(621)
            make.bottom.equalToSuperview().offset(-20)
        }
    }
    
    lazy var titleL: UILabel = {
        let l = UILabel()
        l.text = "预警统计"
        l.font = .systemFont(ofSize: 20)
        l.textColor = .white
        return l
    }()
    
    lazy var reportIV: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "report"))
        iv.contentMode = .scaleAspectFit
        return iv
    }()
    
    lazy var deptBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("上海银行", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 12)
        btn.setImage(UIImage(systemName: "chevron.down"), for: .normal)
        let space = 20.0
        btn.contentHorizontalAlignment = .center //默认
        btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -2.0/space, bottom: 0, right: 2.0/space)
        btn.titleEdgeInsets = UIEdgeInsets(top: 0,  left: 2.0/space, bottom: 0, right: -2.0/space)
        btn.transform = CGAffineTransformMakeScale(-1, 1) //自身旋转180度
        btn.imageView?.transform = CGAffineTransformMakeScale(-1, 1)
        btn.titleLabel?.transform = CGAffineTransformMakeScale(-1, 1)
        btn.backgroundColor = .hex("#3162E1")
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 2
        btn.tintColor = .white
        return btn
    }()
}

class AlarmReportContentView: UIView {
        
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reloadUI(withModel model: AlarmStaticsModal?) {
        numL.text = "\(model?.yjTotal ?? 0)"
        cicleL.text = "环比上月减少 \(model?.hbTotal ?? 0)（\(model?.hbRatio ?? "0")%）"
    }
    
    // MARK: - Setup
    func setupUI() {
        addSubview(chartIV)
        chartIV.snp.makeConstraints { make in
            make.centerX.width.top.equalToSuperview()
            make.width.equalTo(225)
        }
        
        addSubview(nameL)
        nameL.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(103)
        }
        
        addSubview(numL)
        numL.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(nameL.snp.bottom).offset(20)
        }
        
        addSubview(cicleL)
        cicleL.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(numL.snp.bottom).offset(40)
        }
    }
    
    lazy var chartIV: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "ic_alarm_circle"))
        iv.contentMode = .scaleAspectFit
        return iv
    }()
    
    lazy var nameL: UILabel = {
        let l = UILabel()
        l.text = "本月预警数量"
        l.font = .systemFont(ofSize: 14)
        l.textColor = .black
        return l
    }()
    
    lazy var numL: UILabel = {
        let l = UILabel()
        l.text = "0"
        l.font = .systemFont(ofSize: 26)
        l.textColor = .black
        return l
    }()
    
    lazy var cicleL: UILabel = {
        let l = UILabel()
        l.text = "环比上月减少 0（0.0%）"
        l.font = .systemFont(ofSize: 15)
        l.textColor = .hex("#7C766B")
        return l
    }()
}

class AlarmStatisticsView: UIView {
    let dateV = AlarmDateView()
    var collectionView: UICollectionView!
    let aaChartView = AAChartView()
    let contV = AlarmReportContentView()

    var datas: [AlarmStaticsTypeListModal] = []
    
    open var handleWith:((_ m: AlarmStaticsTypeListModal) -> ())?

    var isChart: Bool = false {
        didSet {
            contV.isHidden = isChart
            aaChartView.isHidden = !isChart
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 10
        layer.masksToBounds = true
        backgroundColor = .white
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func exchangeTapped() {
        self.isChart = !isChart
    }
    
    // MARK: -
    func reloadUI(withModel model: AlarmStaticsModal?) {

        contV.reloadUI(withModel: model)
        
        var sjqsDates: [String] = []
        var sjqsTotals: [Int64] = []

        if let sjqs = model?.zxtList {
            sjqs.forEach { s in
                if let date = s.date {
                    sjqsDates.append(date)
                }
                
                if let total = s.total {
                    sjqsTotals.append(total)
                }
            }
        }
        
        let gradientColorDic1 = AAGradientColor.linearGradient(
            direction: .toBottom,
            startColor: AARgba(230, 232, 238, 1),
            endColor: AARgba(230, 232, 238, 0.14)
        )
        
        let numChartModel = AAChartModel()
            .chartType(.area)
            .categories(sjqsDates)
            .xAxisVisible(true)
            .markerRadius(4)
            .markerSymbolStyle(.innerBlank)
            .markerSymbol(.circle)
            .legendEnabled(false)
            .dataLabelsEnabled(false)
            .series([
                AASeriesElement()
                    .name("")
                    .lineWidth(2)
                    .color("#3C72FF")
                    .fillColor(gradientColorDic1)
                    .data(sjqsTotals),
                ])

        aaChartView.aa_refreshChartWholeContentWithChartModel(numChartModel)
    
        let models = model?.typeList?.filter({$0.dictValue != "5" && $0.dictValue != "6"})
        datas = models ?? []
//        datas = model?.typeList ?? []
        collectionView.reloadData()
    }

    // MARK: - Setup
    
    func setupUI() {
        addSubview(dateV)
        dateV.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(35)
            make.right.equalToSuperview().offset(-72)
        }
        
        let exchangeBtn = UIButton(type: .custom)
        exchangeBtn.setImage(UIImage(named: "ic_exchange"), for: .normal)
        exchangeBtn.backgroundColor = .hex("#3C72FF")
        exchangeBtn.layer.masksToBounds = true
        exchangeBtn.layer.cornerRadius = 4
        exchangeBtn.addTarget(self, action: #selector(exchangeTapped), for: .touchUpInside)
        addSubview(exchangeBtn)
        exchangeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(dateV.snp.centerY)
            make.width.height.equalTo(22)
            make.right.equalToSuperview().offset(-16)
        }
        
        aaChartView.frame = CGRect(x: 30, y: 60, width: ScreenWidth - 80, height: 230)
        aaChartView.isHidden = true
        addSubview(aaChartView)
        aaChartView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(100)
            make.left.right.equalToSuperview()
            make.height.equalTo(230)
        }
        
        let aaChartModel = AAChartModel()
            .chartType(.pie)
            .backgroundColor(AAColor.white)
            .dataLabelsEnabled(false)
            .legendEnabled(false)
            .tooltipEnabled(false)
            .series([])
        aaChartView.aa_drawChartWithChartModel(aaChartModel)
        
        addSubview(contV)
        contV.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(100)
            make.left.right.equalToSuperview()
            make.height.equalTo(230)
        }
       
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: (ScreenWidth - 80)/3, height: 120)
        layout.scrollDirection = .vertical
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = .clear
        collectionView.isScrollEnabled = false
        collectionView.register(AlarmStatisticsCell.self, forCellWithReuseIdentifier: "AlarmStatisticsCell")
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(contV.snp.bottom).offset(40)
            make.bottom.equalTo(self.snp.bottom).offset(-20)
            make.width.equalTo(ScreenWidth - 60)
            make.centerX.equalTo(self.snp.centerX)
            make.height.equalTo(264)
        }
    }
}

extension AlarmStatisticsView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AlarmStatisticsCell", for: indexPath)
        
        let data = datas[indexPath.item]
        
        (cell as! AlarmStatisticsCell).reload(withModal: data)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let data = datas[indexPath.item]
        handleWith?(data)
    }
}

